<template>
  <div class="block">
    <div display="block">
      <div align="left">
        <b align="left">{{field.string}}</b></div>
      <div align="right">
        <Icon align="right" name="add-o" style="right: 10px;" @click="onAdd"></Icon>
      </div>

      <div>

        <CellGroup>
          <template v-for="(item,index) in dataRecord">
            <SwipeCell :key="item.value.id">
              <Cell :key="index" :title="item.value.display_name"
                    @click="$router.push({name:'Form',params:{model:field.relation,id:item.value.id}})"
                    clickable></Cell>
              <template #right>
                <Button square type="danger" text="删除" @click="onRemove(item)"/>
                <Button square type="primary" text="编辑" @click="onEdit(item)"/>
              </template>
            </SwipeCell>
          </template>
        </CellGroup>
      </div>
    </div>
  </div>
</template>

<script>
  import Vue from 'vue'
  import gql from 'graphql-tag'
  import Tag from '../ctrls/Tag'
  import {Button, Card, Cell, CellGroup, Icon, SwipeCell} from 'vant'
  import Many from '../ctrls/Many'

  export default {
    name: 'Many2manyForm',
    components: {Tag, Card, Icon, Many, CellGroup, Cell, SwipeCell, Button},
    props: {
      field: {
        type: Object,
        default() {
          return {}
        }
      },
      edit: {type: Boolean, defautl: false},
      model: {type: String, default: ''},
      id: {type: Number, default: 0},
      saveFast: {type: Boolean, default: true},
      widget: {type: String, default: 'table'}
    },
    inject: ['value'],
    data: function () {
      return {
        newval: this.value.cval,
      }
    },
    apollo: {
      dataRecord: {
        query: gql`query qdv($model:String,$domain:String!,$queryFields:[String]){
                   dataRecord:allRecord(model:$model,domain:$domain,fields:$queryFields){
            value
          }
         }`,
        variables() {
          return {
            model: this.field.relation,
            domain: JSON.stringify([['id', 'in', this.newval]]),
            queryFields: ['id', 'display_name']
          }
        },
        skip() {
          return !(this.field.relation && this.newval && (this.newval.length > 0))
        }
      },
      allRecord: {
        query: gql`query qdv($model:String,$domain:String!,$queryFields:[String]){
                   allRecord:allRecord(model:$model,domain:$domain,fields:$queryFields,limit:999){
            value
          }
         }`,
        variables() {
          return {
            model: this.field.relation,
            domain: JSON.stringify([]),
            queryFields: ['id', 'display_name']
          }
        },
        skip() {
          return !this.field.relation
        }
      }
    },
    computed: {
      writeDict() {
        let v = {}
        v[this.field.name] = [[6, 0, this.newval]]
        v[this.field.relation_field] = this.id
        return v
      },
    },
    watch: {},
    mounted: function () {

      this.$EventBus.$on(this.field.name, (ids) => {
        console.info(ids)
        this.newval = ids
        this.onValueChange(ids)
      })
    },
    methods: {
      onValueChange: function (val) {
        if (this.saveFast) {
          let self = this
          this.$apollo.mutate({
            mutation: gql`mutation($id:Int!,$model:String!,$value:JSON!){
  writeRecord(id:$id,model:$model,value:$value){
    ok
  }
}`,
            variables: {id: this.id, model: this.model, value: this.writeDict}
          }).then(function (response) {
            if (response && response.data.writeRecord.ok) {
            } else if (response && !response.data.writeRecord.ok) {
              self.$message.error(response.data.errMsg)
            }
          })
            .catch(function (error) {
              console.log(error, __filename)
              self.$message.error(error)
            })
        } else {
          Vue.set(this.value, 'newval', this.newval)
          Vue.set(this.value, 'change', this.value.cval !== this.newval)
        }
      },
      onRemove(item) {
        const index = this.newval.indexOf(item.value.id)
        if (index > -1) {
          this.newval.splice(index, 1)
          this.onValueChange()
        }
      }, onAdd() {
        this.$router.push({
          name: 'pagemany',
          query: {
            field: this.field,
            model: this.model,
            id: this.id,
            type: 'many2many',
            ids: this.value,
            emit_name: this.field.name
          }
        })
      }, onEdit(item) {
        this.$router.push({
          name: 'EditForm',
          params: {
            model: this.field.relation,
            id: item.value.id,
          },
          query: {
            field: this.field,
            model: this.model,
            id: this.id,
            type: 'many2many',
            ids: this.value,
            emit_name: this.field.name
          }
        })
      },
    }
  }
</script>

<style type="less">

</style>
